package com.zp.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.entity.ClinicIndex;
import com.zp.base.entity.ClinicSchedule;
import com.zp.base.entity.bo.ClinicScheduleBo;
import com.zp.base.entity.vo.ClinicScheduleVo;
import com.zp.base.mapper.ClinicIndexMapper;
import com.zp.base.mapper.ClinicScheduleMapper;
import com.zp.base.service.IClinicScheduleService;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 出诊安排Service业务层处理
 *
 * @author zhang peng
 * @date 2023-01-16
 */
@RequiredArgsConstructor
@Service
public class ClinicScheduleServiceImpl implements IClinicScheduleService {

    private final ClinicScheduleMapper baseMapper;
    private final ClinicIndexMapper clinicIndexMapper;

    /**
     * 查询出诊安排
     */
    @Override
    public ClinicScheduleVo queryById (String scheduleId) {
        return baseMapper.selectVoById(scheduleId);
    }

    /**
     * 查询出诊安排列表(分页)
     */
    @Override
    public TableDataInfo<ClinicScheduleVo> queryPageList (ClinicScheduleBo bo, PageQuery pageQuery) {
        List<ClinicIndex> indexList = clinicIndexMapper.selectList(Wrappers.<ClinicIndex>lambdaQuery()
                .eq(ClinicIndex::getOrgId, bo.getOrgId()));
        LambdaQueryWrapper<ClinicSchedule> lqw = buildQueryWrapper(bo);
        Page<ClinicScheduleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtil.isNotEmpty(indexList)) {
            result.getRecords().forEach(item -> {
                item.setClinicIndexName(indexList.stream().filter(i -> StringUtils.equals(i.getClinicIndexId(), item.getClinicIndexId())).findAny().get().getName());
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询出诊安排列表(不分页)
     */
    @Override
    public List<ClinicScheduleVo> queryList (ClinicScheduleBo bo) {
        LambdaQueryWrapper<ClinicSchedule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ClinicSchedule> buildQueryWrapper (ClinicScheduleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ClinicSchedule> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getClinicIndexId()), ClinicSchedule::getClinicIndexId, bo.getClinicIndexId());
        lqw.eq(StringUtils.isNotBlank(bo.getDayOfWeek()), ClinicSchedule::getDayOfWeek, bo.getDayOfWeek());
        lqw.eq(StringUtils.isNotBlank(bo.getTimeDesc()), ClinicSchedule::getTimeDesc, bo.getTimeDesc());
        lqw.eq(bo.getLimitNum() != null, ClinicSchedule::getLimitNum, bo.getLimitNum());
        lqw.eq(bo.getLimitPreNum() != null, ClinicSchedule::getLimitPreNum, bo.getLimitPreNum());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), ClinicSchedule::getOrgId, bo.getOrgId());
        return lqw;
    }

    /**
     * 新增出诊安排
     */
    @Override
    public Boolean insertByBo (ClinicScheduleBo bo) {
        List<ClinicSchedule> list = baseMapper.selectList(Wrappers.<ClinicSchedule>lambdaQuery()
                .eq(StringUtils.isNotEmpty(bo.getClinicIndexId()), ClinicSchedule::getClinicIndexId, bo.getClinicIndexId()));

        // 过滤页面取消选中的号别安排，(差集)
        List<ClinicSchedule> differenceSetAList = list.stream().filter(a ->
                !bo.getSaveInfoList().stream().map(ClinicSchedule::getScheduleId).collect(Collectors.toList()).contains(a.getScheduleId())
        ).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(differenceSetAList)) {
            baseMapper.deleteBatchIds(differenceSetAList.stream().map(ClinicSchedule::getScheduleId).distinct().collect(Collectors.toList()));
        }
        bo.getSaveInfoList().forEach(item -> {
            item.setOrgId(bo.getOrgId());
            item.setClinicIndexId(bo.getClinicIndexId());
            item.setLimitNum(item.getLimitNum() == null ? Long.valueOf(0) : item.getLimitNum());
            item.setLimitPreNum(item.getLimitPreNum() == null ? Long.valueOf(0) : item.getLimitPreNum());
            item.setDelFlag("0");
            if (list.stream().anyMatch(e -> StringUtils.equals(e.getScheduleId(), item.getScheduleId()))) {
                baseMapper.updateById(item);
            } else {
                baseMapper.insert(item);
            }
        });
        return true;
    }

    /**
     * 修改出诊安排
     */
    @Override
    public Boolean updateByBo (ClinicScheduleBo bo) {
        ClinicSchedule update = BeanUtil.toBean(bo, ClinicSchedule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (ClinicSchedule entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除出诊安排
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
